﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Windows.Forms;

namespace Ecosystème
{
    class Arborescence
    {
        
        private XmlTextReader lecturexml;
        String cheminXml;
        TreeView tv;


        public Arborescence(String chemin, TreeView nomTv)
        {
            this.cheminXml = chemin;
            this.tv = nomTv;
            this.ChargerArbre();          
        }

        private void ChargerArbre()
        {
            try
            {
                // SECTION 1. Create a DOM Document and load the XML data into it.
                XmlDocument dom = new XmlDocument();
                lecturexml = new XmlTextReader(cheminXml);
                dom.Load(lecturexml);

                // SECTION 2. Initialize the TreeView control.
                tv.Nodes.Clear();
                tv.Nodes.Add(new TreeNode(dom.DocumentElement.Name));
                TreeNode tNode = new TreeNode();
                tNode = tv.Nodes[0];

                // SECTION 3. Populate the TreeView with the DOM nodes.
                ajouterNoeud(dom.DocumentElement, tNode);
                tv.ExpandAll();

            }
            catch (XmlException xmlEx)
            {
                MessageBox.Show(xmlEx.Message);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

        private void ajouterNoeud(XmlNode inXmlNode, TreeNode inTreeNode)
        {
            XmlNode xNode;
            TreeNode tNode;
            XmlNodeList nodeList;
            int i;

            // Loop through the XML nodes until the leaf is reached.
            // Add the nodes to the TreeView during the looping process.
            if (inXmlNode.HasChildNodes)
            {
                nodeList = inXmlNode.ChildNodes;
                for (i = 0; i <= nodeList.Count - 1; i++)
                {
                    xNode = inXmlNode.ChildNodes[i];
                    inTreeNode.Nodes.Add(new TreeNode(xNode.Name));
                    tNode = inTreeNode.Nodes[i];
                    ajouterNoeud(xNode, tNode);
                }
            }
            else
            {
                // Here you need to pull the data from the XmlNode based on the
                // type of node, whether attribute values are required, and so forth.
                inTreeNode.Text = (inXmlNode.OuterXml).Trim();
            }
        }      
    }
}
